package org.uu.service;

import com.auth0.jwt.interfaces.Claim;
import org.jose4j.jwt.JwtClaims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.uu.bean.User;
import org.uu.common.CommonResult;
import org.uu.jwt.JwtTools;
import org.uu.repository.UserDao;

import java.util.Map;
import java.util.Objects;

@Service
public class UserService {

    @Autowired
    UserDao userDao;

    public ResponseEntity<String> addUser(User user, String token) {
        Map<String, Claim> claimMap = JwtTools.verifyToken4HS256(token);
        Claim user_id = claimMap.get("user_id");
        Claim userRole = claimMap.get("user_role");
        int result = 0;
        if (userRole.asInt() == 7) {
            result = userDao.addUser(user);
        } else {
            return ResponseEntity.status(403).body("user_id: " + user_id + " 权限不足");
        }

        return ResponseEntity.ok(user.getId() + " 创建完成, code: " + result);
    }

    public CommonResult getUser(User user, String token) {
        CommonResult commonResult = new CommonResult<>();

        JwtClaims jwtClaims = JwtTools.verifyToken4RS256(token);
        String user_id = (String) jwtClaims.getClaimsMap().get("user_id");
        Integer userRole = (Integer) jwtClaims.getClaimsMap().get("user_role");

        User result = null;
        if (userRole == 4) {
            result = userDao.getUserById(user);
        } else {
            commonResult.setCode(403);
            commonResult.setMessage("user_id: " + user_id + " 权限不足");
//                commonResult.setData();
            return commonResult;
        }
        commonResult.setMessage("OK");
        commonResult.setCode(200);
        commonResult.setData(result);

        return commonResult;
    }

    public String login(User user) {
        User targetUser = userDao.checkUser(user);
        String token = "";
        if (Objects.nonNull(targetUser)) {
            token = JwtTools.createToken4RS256(user);
        }
        return token;

    }
}
